<template>
	<view v-if="showCamera" class="camera-box">
		<camera :device-position="cameraDirection" :flash="flashText" style="width: 100%; height: 100vh" mode="normal"
			@error="errorCamera">
			<!-- 图片控件 -->
			<block class="imgViewBox" v-if="tempImagePath">
				<cover-image class="imageView" :src="tempImagePath" />
				<cover-view class="btn-group flex_between check-box">
					<cover-view @click="tempImagePath = ''">
						<cover-image class="icon" src="@/static/images/camera/cancel.png" />
					</cover-view>
					<cover-view @click="upload">
						<cover-image class="icon" src="@/static/images/camera/checked.png" />
					</cover-view>
				</cover-view>
			</block>
			<!-- 相机控件 -->
			<block v-else>
				<cover-view class="btn-group flex_center">
					<cover-view v-if="flOpen" class="albumLeft">
						<cover-image @click="flClick" v-if="flState" class="albumLeft_img"
							src="@/static/images/camera/flOpen.png" />
						<cover-image @click="flClick" v-else class="albumLeft_img"
							src="@/static/images/camera/flClose.png" />
						<cover-view>手电筒</cover-view>
					</cover-view>
					<cover-view class="take-photos" @click="takePhoto">
						<cover-image class="take-photos_img" src="@/static/images/camera/beat.png" />
						<cover-view>拍照</cover-view>
					</cover-view>
					<cover-view class="albumRight" v-if="false" @click="chooseImage">
						<cover-image class="albumRight_img"
							src="https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/album.png" />
						<cover-view>相册</cover-view>
					</cover-view>
					<cover-view class="albumRight" @click="cameraDirectionClick">
						<cover-image class="albumRight_img" src="@/static/images/camera/cameraDirection.png" />
						<cover-view>切换</cover-view>
					</cover-view>
				</cover-view>
			</block>
		</camera>
		<!-- helangCompress-压缩图片 -->
		<f-compressImg ref="helangCompress" />
	</view>
</template>

<script>
	// import {
	// 	getPermission
	// } from '@/tools/utils.js'
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				showCamera: false, // 相机显/隐
				tempImagePath: '',
				statusBarHeight: 44,
				flOpen: true, // 闪光灯整体显/隐
				flashText: 'off', // 闪光灯打开关闭显/隐
				flState: false, // 闪光灯状态显/隐
				cameraDirection: 'back', // 相机反转前/后
				cacheDevicePics: [], // 本地缓存的设备照片（后台返回的照片+新拍的照片）
				firePracticeImgsList: [] // 执业图片
			}
		},
		onLoad(options) {
			// console.log('前边页面传过来的参数---', JSON.parse(options.params))
			this.getInitiaCamera() // 相机初始化
			const params = JSON.parse(options.params)
			this.cacheDevicePics = params.cacheDevicePics
			this.firePracticeImgsList = params.firePracticeImgsList
		},
		onShow() {
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 10
			this.getInitiaCamera() // 相机初始化
		},
		computed: {
			...mapState({
				userInfo: modules => modules.infoList.userInfo
			})
		},
		methods: {
			// 初始化相机
			getInitiaCamera() {
				let that = this
				that.showCamera = true // 相机显/隐
				// uni.showLoading({
				// 	mask: true,
				// 	title: '相机初始化···'
				// })
				// setTimeout(() => {
				// 	uni.hideLoading()
				// 	that.showCamera = true
				// }, 10)
			},
			// 打开闪光灯
			flClick() {
				if (this.flState) {
					this.flashText = 'off'
					this.flState = false
				} else {
					this.flashText = 'torch' // 打开手电筒
					this.flState = true
				}
			},
			// 打开相册
			chooseImage() {
				uni.chooseImage({
					count: 1,
					sourceType: ['album'], // 只能从相册选图片
					success: (res) => {
						this.tempImagePath = res.tempFilePaths[0]
					}
				})
			},
			// 相机前后摄像头切换
			cameraDirectionClick() {
				if (this.cameraDirection == 'front') {
					this.cameraDirection = 'back'
					this.flOpen = true
				} else {
					this.cameraDirection = 'front'
					this.flOpen = false
					this.flashText = 'off'
					this.flState = false
				}
			},
			// 拍照
			takePhoto() {
				let that = this
				const ctx = uni.createCameraContext()
				ctx.takePhoto({
					success: (res) => {
						that.flState = false
						that.tempImagePath = res.tempImagePath
					}
				})
			},
			// 上传照片
			upload() {
				let that = this;
				uni.showLoading({
					mask: true,
					title: '上传中，请稍后'
				})
				that.$refs.helangCompress
					.compress({
						src: that.tempImagePath,
						// maxSize: 800,
						// fileType: 'jpg',
						quality: 0.9,
						// minSize: 640 //最小压缩尺寸，图片尺寸小于该时值不压缩，非H5平台有效。若需要忽略该设置，可设置为一个极小的值，比如负数。
					})
					.then(res => {
						// console.log('压缩成功回调返回图片地址------', res);
						that.firePracticeImgsList.push({
							id: '', //  Date.now(),
							creater: that.userInfo.id,
							attachUrl: res
						}); // 把新拍的照片存到照片集合中
						let names = +new Date().getTime();
						let imgs = {
							id: '', // Date.now(),
							creater: that.userInfo.id,
							names: names,
							attachUrl: res,
							tips: 1, // 新拍的照片标识为1
							nums: that.cacheDevicePics.length + 1
						};
						that.cacheDevicePics.push(imgs); // 缓存的照片
						uni.hideLoading()
						uni.showToast({
							icon: 'success',
							title: '上传成功'
						})
						setTimeout(() => {
							that.back()
						}, 500)
						// 图片保存到本地（用户想把拍的照片保存到本地）
						uni.saveImageToPhotosAlbum({
							filePath: res,
							success: function() {},
							fail() {
								this.$showModal('您拒绝了图片保存到系统相册')
							}
						});
					})
					.catch(() => {
						// 压缩失败回调
						// console.log('压缩失败回调', err);
						uni.showToast({
							title: '上传失败，请重新上传',
							icon: 'none',
							duration: 2000
						});
					});
			},
			// 返回上一个页面
			back() {
				uni.$emit('refreshPreviousPage', {
					cacheDevicePics: this.cacheDevicePics,
					firePracticeImgsList: this.firePracticeImgsList
				});
				setTimeout(() => {
					uni.navigateBack({
						delta: 1,
					});
				}, 10)
			},
			// 相机初始化失败返回
			errorCamera(e) {
				this.$showModal('相机打开失败')
				console.error('相机初始化失败', e)
				uni.getSetting({
					success(res) {
						if (!res.authSetting["scope.camera"]) {
							uni.showModal({
								title: '提示',
								content: '请开启摄像头权限，否则无法拍照',
								confirmText: '去开启',
								success(res) {
									if (res.confirm) {
										uni.openSetting({
											success(res) {
												if (res.authSetting["scope.camera"]) {
													uni.navigateBack({
														delta: 1
													})
												} else {
													uni.navigateBack({
														delta: 1
													})
												}
											}
										})
									} else if (res.cancel) {
										uni.navigateBack({
											delta: 1
										})
									}
								}
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.camera-box {
		width: 100%;
		height: 100vh;
		text-align: center;
		color: white;
		position: fixed;
		background: url('https://fire-system.oss-cn-beijing.aliyuncs.com/web/fire-technology/cameraBg.png') no-repeat;
		background-size: cover;

		.imgViewBox {
			position: fixed;
			left: 0;
			top: 0;
			width: 100%;
			height: 100vh;
			z-index: 9;
		}

		.imageView {
			width: 100%;
			height: 100%;
		}

		.btn-group {
			width: 100%;
			z-index: 999;
			position: fixed;
			bottom: 100rpx;

			.take-photos {
				font-size: 24rpx;
				font-weight: 400;

				&_img {
					width: 120rpx;
					height: 120rpx;
					margin-bottom: 30rpx;
				}
			}

			.albumLeft {
				position: absolute;
				bottom: 0rpx;
				left: 80rpx;
				font-size: 24rpx;
				font-weight: 400;

				&_img {
					width: 83rpx;
					height: 83rpx;
					margin: 0 0 30rpx 15rpx;
				}
			}

			.albumRight {
				position: absolute;
				bottom: 0rpx;
				right: 80rpx;
				font-size: 24rpx;
				font-weight: 400;

				&_img {
					width: 88rpx;
					height: 88rpx;
					margin-bottom: 30rpx;
				}
			}

			&.check-box {
				padding: 0 110rpx;
				box-sizing: border-box;

				.icon {
					width: 70rpx;
					height: 70rpx;
				}
			}
		}

		.flex_center {
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.flex_between {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		@keyframes scan {
			0% {
				top: 23vh;
				opacity: 0;
			}

			15% {
				opacity: 1;
			}

			90% {
				opacity: 1;
			}

			100% {
				top: 55.5vh;
				opacity: 0;
			}
		}
	}
</style>